/**
 * 
 */
package com.panda.ServletDemo.utils;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.templateresolver.ITemplateResolver;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;

/**
 * Thymeleaf模版配置
 * @author pcongda
 * @version 1.0
 * 
 */
@WebListener(value="engineListener")
public class ThymeleafUtil implements ServletContextListener{
	
	private static final Logger logger = LoggerFactory.getLogger(ThymeleafUtil.class);
	
	@Override
	public void contextInitialized(ServletContextEvent sce) {
		String contextPath = sce.getServletContext().getContextPath();
		//保存web根目录
		sce.getServletContext().setAttribute("cxtPath", contextPath);
	    logger.info("初始化模版,参数为:{}",contextPath);
	}
	
	//获取模版
 	public static TemplateEngine templateEngine(ServletContext servletContext) {
        TemplateEngine engine = new TemplateEngine();
        engine.setTemplateResolver(templateResolver(servletContext));
        return engine;
    }
	
 	//模版配置信息
 	private static ITemplateResolver templateResolver(ServletContext servletContext) {
         ServletContextTemplateResolver resolver = new ServletContextTemplateResolver(servletContext);
         resolver.setCharacterEncoding("UTF-8");
         resolver.setTemplateMode("HTML");
         resolver.setPrefix("/templates/");
         resolver.setSuffix(".html");
         resolver.setCacheable(false); //禁用缓存
         return resolver;
    }
 	
	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		sce = null;
	}

}
